//
//  MineProfileController.swift
//  MT
//
//  Created by M on 2019/12/29.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import YPNavigationBarTransition
import IQKeyboardManagerSwift

class MineProfileController: BaseViewController {
    
    /// 个人
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    /// 上传
    private lazy var upload_provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    /// 标签
    private lazy var tag_provider: MTProvider<TagApi> = {
        return MTProvider<TagApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    /// 上传回调
    typealias UploadSuccessHandler = (_: Bool) -> Swift.Void
    
    /// 个人信息
    var model: MineInfoModel?
    
    /// 个人标签
    var tagResults: [MTTagModel]?
    /// 兴趣标签
    var hobbyResults: [MTTagModel]?
    
    /// 当前选中的相册 Index - 用于相册选图后的位置标识
    private var currentSelectedIndex: Int = -1

    lazy var tableView: MineProfileTableView = {
        let tv = MineProfileTableView(frame: self.view.bounds)
        tv.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0)
        tv.interactionDelegate = self
        return tv
    }()
    
    deinit {
        removeNotifications()
    }
    
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MineProfileController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        requestTags(withTagType: 1)
        requestTags(withTagType: 2)
        setup()
        initializeUI()
        setTableViewDatas()
        addNotifications()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableView.reloadData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
}


// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MineProfileController {
    
    private func setup() {
        let r_btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 24))
        r_btn.setBackgroundImage(UIImage(color: UIColor(hex: 0x5d5d5d)), for: .disabled)
        r_btn.setBackgroundImage(UIImage(color: UIColor.theme.main), for: .normal)
        r_btn.setTitle("保存", for: .normal)
        r_btn.setTitleColor(.black, for: .normal)
        r_btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        r_btn.adjustsImageWhenHighlighted = false
        r_btn.layer.cornerRadius = 12
        r_btn.clipsToBounds = true
        r_btn.addTarget(self, action: #selector(mineProfileController(didClickSaveButton:)), for: .touchUpInside)
        let rightButton = UIBarButtonItem(customView: r_btn)
        self.navigationItem.rightBarButtonItem = rightButton
        
        self.navigationItem.title = "编辑个人信息"
        
    }
    
    private func initializeUI() {
        view.addSubview(tableView)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalTo(view).offset(NavigationBarHeight+StatusBarHeight)
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(ScreenHeight - NavigationBarHeight - StatusBarHeight)
        }
    }
    
    private func setTableViewDatas() {
//        tableView.imageAsset = model.headerUrl
        tableView.headURL = model?.headerUrl
        tableView.nickname = model?.nickname
        tableView.location = model?.area
        tableView.birthday = model?.birthday
        tableView.signature = model?.signature
        tableView.body_height = model?.height
        tableView.body_weight = model?.weight
        tableView.constellation = model?.constellation
        tableView.occupation = model?.industry
        tableView.occupation_position = model?.position
        tableView.school = model?.school
        tableView.degree = model?.degree
        if let tags = model?.tagList {
            tableView.tags = tags
        }
        if let hobbies = model?.hobbyList {
            tableView.hobbies = hobbies
        }
        tableView.reloadData()
    }
    
}


// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MineProfileController {
    
    /// 点击返回按钮
    private func mineProfileController(didClickPopButton sender: UIBarButtonItem) {
        if navigationController?.viewControllers.count ?? 0 > 1 {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    /// 点击保存按钮
    private func mineProfileController(didClickSaveButton sender: UIBarButtonItem) {
        self.tableView.endEditing(true)
        if let asset = tableView.imageAsset {
            if let model = UserMediaListModel(JSON: ["localAsset": asset,
                                                     "objType": asset.mediaType == .video ? 1 : 0]) {
                model.uploadStatus = .ready
                upload(model: model, currentIdx: currentSelectedIndex) { (flag) in
                    debugPrint(flag)
                }
            }
        }
    }
}

// MARK: ------------------ 通知相关 ----------------------
extension MineProfileController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(presentPhotoLibrary), name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }
    
}

// MARK: ------------------------------------ 数据请求相关 ----------------------------------------
extension MineProfileController {
    
    /// 请求标签
    private func requestTags(withTagType type: Int) {
        tag_provider.rx.requestResult(.list(type: type)).subscribe(onNext: { [weak self] (result: Result<MTTagResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let code = response.code, code == 200, var result = response.result {
                    if let otherTag = MTTagModel(JSON: ["name": "其它 +"]) {
                        result.append(otherTag)
                    }
                    if type == 1 {
                        weakself.tagResults = result
                    } else if type == 2 {
                        weakself.hobbyResults = result
                    }
                }
                break
                
            case .failure:
                break
            }
            
        }).disposed(by: disposeBag)
    }
        
    /// 更新普通个人数据
    private func updatePersonalInfos() {
        var params: [String: Any] = [:]
        if let headerUrl = self.tableView.headURL {
            params["headerUrl"] = headerUrl
        }
        if let nickname = self.tableView.nickname, nickname != "" {
            params["nickname"] = nickname
        }
        if let location = self.tableView.location {
            params["area"] = location
        }
        if let signature = self.tableView.signature {
            params["signature"] = signature
        }
        if let birthday = self.tableView.birthday {
            params["birthday"] = birthday
        }
        if let body_height = self.tableView.body_height {
            params["height"] = body_height
        }
        if let body_weight = self.tableView.body_weight {
            params["weight"] = body_weight
        }
        if let constellation = self.tableView.constellation {
            params["constellation"] = constellation
        }
        if let occupation = self.tableView.occupation, occupation != "" {
            params["industry"] = occupation
        }
        if let occupation_position = self.tableView.occupation_position, occupation_position != "" {
            params["position"] = occupation_position
        }
        if let school = self.tableView.school, school != "" {
            params["school"] = school
        }
        if let degree = self.tableView.degree {
            params["degree"] = degree
        }
        
        let group = DispatchGroup()
        
        group.enter()
        provider.rx.requestResult(.userInfoModify(params)).subscribe(onNext: { (result: Result<MineInfoListResponseModel, AnyError>, isCache: Bool) in
            switch result {
            case let .success(response):
                if let code = response.code, code == 200 {
                    group.leave()
                } else {
                    DispatchQueue.main.async {
                        AlertManager.presentAlertView(message: "修改失败")
                    }
                }
                break
            case let .failure(error):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break
            }
        }).disposed(by: disposeBag)

        group.notify(queue: .main) {
            NotificationCenter.default.post(name: GlobalNotificationName.refreshUserInfo.name, object: nil)
            AlertManager.presentAlertView(message: "修改成功")
            self.navigationController?.popToRootViewController(animated: true)
        }
        
    }

    /// 上传视频或图片
    private func save(withModel model: UserMediaListModel, currentIdx: Int, successHandler: UploadSuccessHandler) {
        var params: [String: Any] = model.toJSON()
        params["sort"] = currentIdx
        provider.rx.requestResult(.userMediaInfoSave(params)).subscribe(onNext: { [weak self] (result: Result<UserMediaListResponseModel, AnyError>, isCache) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let code = response.code, code == 200 {
                    DispatchQueue.main.async {
                        model.id = response.result?.id
                        model.uploadProgress = 1
                        model.uploadStatus = .finished
                        weakself.tableView.reloadData()
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }).disposed(by: disposeBag)
    }
    
//    /// 删除视频或图片
//    private func delete(withModel model: UserMediaListModel, currentIdx: Int) {
//        guard let id = model.id else { return }
//
//        provider.originRequest(.userMediaInfoDelete(id), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
//            guard let weakself = self else { return }
//            switch result {
//            case let .success(response):
//                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
//                    DispatchQueue.main.async {
//                        weakself.tableView.imgList?.remove(at: currentIdx)
//                        weakself.tableView.reloadData()
//                    }
//                } else {
//
//                }
//                break
//
//            case .failure(_):
//                break
//            }
//        }
//
//    }
    
}

// MARK: ------------------------------------ 上传相关 ----------------------------------------
extension MineProfileController {
    
    /// 上传模型
    private func upload(model: UserMediaListModel, currentIdx: Int, successHandler: @escaping UploadSuccessHandler) {
        if model.uploadStatus != .ready { return }
        guard let asset = model.localAsset else { return }
        
        if asset.mediaType == .video {
            var coverImage: UIImage?
            var videoPath: String?
            let group = DispatchGroup()
            var progressGroup = [Double](repeating: 0, count: 2)
            /// 获取封面图
            group.enter()
            MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth, progressHandler: { [weak self] (progress) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    if model.uploadStatus != .ready {
                        model.uploadStatus = .ready
                    }
                    progressGroup[0] = progress
                    model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.1, doneProgress: 0)
//                    weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                }
            }, errorHandler: nil) { (image, info, isDegraded) in
                if isDegraded == false, let image = image {
                    coverImage = image
                    group.leave()
                }
            }
            /// 获取视频
            group.enter()
            MTAssetLibrary.default.requestVideo(withAsset: asset.asset, progressHandler: nil, errorHandler: nil, assetCompletion: nil) { [weak self] (progress, path) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    if progress > 0 {
                        if model.uploadStatus != .ready {
                            model.uploadStatus = .ready
                        }
                        progressGroup[1] = Double(progress)
                        model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.1, doneProgress: 0)
//                        weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                    }
                }
                if let path = path {
                    videoPath = path
                    group.leave()
                }
            }
            
            group.notify(queue: .global()) {
                if let videoPath = videoPath, let coverImage = coverImage {
                    self.uploadVideo(videoPath: videoPath, coverImage: coverImage, model: model, asset: asset, currentIdx: currentIdx, successHandler: successHandler)
                }
            }
            
        } else {
            /// 图片上传
            MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth, progressHandler: { [weak self] (progress) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    if model.uploadStatus != .ready {
                        model.uploadStatus = .ready
                    }
                    model.uploadProgress = weakself.calculateProgress(group: [progress], percentage: 0.1, doneProgress: 0)
//                    weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                }
            }, errorHandler: nil) { [weak self] (image, info, isDegraded) in
                guard let weakself = self else { return }
                if isDegraded == false, let image = image {
                    weakself.upload(image: image, model: model, asset: asset, currentIdx: currentIdx, successHandler: successHandler)
                }
            }
        }
        
    }
    
    /// 上传视频及封面图
    private func uploadVideo(videoPath: String, coverImage: UIImage, model: UserMediaListModel, asset: MTAsset, currentIdx: Int, successHandler: @escaping UploadSuccessHandler) {
        let group = DispatchGroup()
        var progressGroup = [Double](repeating: 0, count: 2)
        group.enter()
        upload_provider.originRequest(.upload(coverImage), callbackQueue: .global(), progress: { [weak self] (progressResonpse) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                if model.uploadStatus != .uploading {
                   model.uploadStatus = .uploading
                }
                progressGroup[0] = progressResonpse.progress
                model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.89, doneProgress: 0)
//                weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
            }
        }) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200, let url = datas["result"] as? String {
                        DispatchQueue.main.async {
                            model.coverImg = url
                            group.leave()
                        }
                    } else {
                        DispatchQueue.main.async {
                            model.uploadStatus = .fail
//                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                        }
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }
        
        group.enter()
        upload_provider.originRequest(.uploadVideo(URL(fileURLWithPath: videoPath)), callbackQueue: .global(), progress: { [weak self] (progressResponse) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                if model.uploadStatus != .uploading {
                   model.uploadStatus = .uploading
                }
                progressGroup[1] = progressResponse.progress
                model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.89, doneProgress: 0)
//                weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
            }
        }) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200, let url = datas["result"] as? String {
                        DispatchQueue.main.async {
                            model.href = url
                            group.leave()
                        }
                    } else {
                        DispatchQueue.main.async {
                            model.uploadStatus = .fail
//                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                        }
                    }
                }
                break
                
            case .failure(_):
                break
            }
        }
        
        group.notify(queue: .main) {
            self.save(withModel: model, currentIdx: currentIdx, successHandler: successHandler)
        }
    }
    
    // MARK: ------------------------------------ 上传图片 ----------------------------------------
    
    /// 上传图片
    private func upload(image: UIImage, model: UserMediaListModel, asset: MTAsset, currentIdx: Int, successHandler: @escaping UploadSuccessHandler) {
        MBProgressHUD_JChat.showProgress(self.view, text: "正在上传头像")
        upload_provider.originRequest(.upload(image), callbackQueue: .global(), progress: { [weak self] (progressResonpse) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                if model.uploadStatus != .uploading {
                    model.uploadStatus = .uploading
                }
                model.uploadProgress = weakself.calculateProgress(group: [progressResonpse.progress], percentage: 0.89, doneProgress: 0.1)
                MBProgressHUD_JChat.modifyProgressHUD(weakself.view, progress: Float(progressResonpse.progress), text: "正在上传头像")
//                weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
            }
        }) { [weak self] (result, _) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    if code == 200, let url = datas["result"] as? String {
                        DispatchQueue.main.async {
                            MBProgressHUD_JChat.dismiss(weakself.view)
                            weakself.save(withModel: model, currentIdx: currentIdx, successHandler: successHandler)
                            model.href = url
                            model.uploadStatus = .finished
                            weakself.tableView.headURL = url
                            weakself.updatePersonalInfos()
//                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                        }
                    } else {
                        DispatchQueue.main.async {
                            model.uploadStatus = .fail
                            MBProgressHUD_JChat.dismiss(weakself.view)
                            MBProgressHUD_JChat.show(text: "图片上传失败", view: weakself.view)
//                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                        }
                    }
                }
                break

            case .failure(_):
                DispatchQueue.main.async {
                    model.uploadStatus = .fail
                    MBProgressHUD_JChat.dismiss(weakself.view)
                    MBProgressHUD_JChat.show(text: "图片上传失败", view: weakself.view)
//                    weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                }
                break
            }
        }
    }
    
    /**
     计算进度
     
     group: 进度数组
     percentage: 此次进度总占比
     doneProgress: 已完成进度
     */
    private func calculateProgress(group: [Double], percentage: Double, doneProgress: Double) -> Double {
        return group.reduce(0, { (r, p) -> Double in
            return r + p
        }) / Double(group.count) * percentage + doneProgress
        
    }
}


// MARK: ------------------------------------ 相册 ----------------------------------------
@objc extension MineProfileController {
    
    private func presentPhotoLibrary(maxCount: Int, allowVideoSelection: Bool) {
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.maxSelectdCount = 1
        c.allowVideoSelection = allowVideoSelection
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
}

// MARK: ------------------------------------ 标签 ----------------------------------------
extension MineProfileController {
    
    private func presentTagController(withType type: MTTagViewController.TagType) {
        let c = MTTagViewController(tagType: type)
        c.delegate = self
        self.navigationController?.pushViewController(c, animated: true)
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ MineProfileTableViewDelegate ----------------------------------------
extension MineProfileController: MineProfileTableViewDelegate {
//
//    func mineProfileTableViewShouldPresentPhotoLibrary(_ tableView: MineProfileTableView, maxSelectCount: Int, type: MineGalleryCollectionViewCell.Status, withIndexPath indexPath: IndexPath) {
//        currentSelectedIndex = indexPath.item
//        switch type {
//        case .selected:
//            let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
//            let a1 = UIAlertAction(title: "替换", style: .default) { (action) in
//                self.presentPhotoLibrary(maxCount: 1, allowVideoSelection: indexPath.item != 0)
//            }
//            let a2 = UIAlertAction(title: "删除", style: .default) { (action) in
//                if let model = self.tableView.imgList?[indexPath.item] {
//                    self.delete(withModel: model, currentIdx: indexPath.item)
//                }
//            }
//            let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//            alertController.addAction(a1)
//            if indexPath.item != 0 { alertController.addAction(a2) }
//            alertController.addAction(cancel)
//            self.present(alertController, animated: true, completion: nil)
//
//            break
//        case .unselected, .unselected_highlighted:
//            presentPhotoLibrary(maxCount: maxSelectCount, allowVideoSelection: true)
//            break
//        }
//    }
    
    func mineprofileTableViewShouldPushToTagController(_ tableView: MineProfileTableView, withType type: MTTagViewController.TagType) {
        presentTagController(withType: type)
    }
    
}

// MARK: ------------------------------------ 相册代理回调 ----------------------------------------
extension MineProfileController: PhotoLibraryViewControllerDelegate {
    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
        if let model = UserMediaListModel(JSON: ["localAsset": asset,
                                                 "objType": asset.mediaType == .video ? 1 : 0]) {
            model.uploadStatus = .ready
            
            tableView.imageAsset = asset
//            self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
//            tableView.imageAsset = asset
        }
//        if let model = UserMediaListModel(JSON: ["localAsset": assets,
//                                                 "objType": assets.mediaType == .video ? 1 : 0]) {
//            model.uploadStatus = .ready
//            upload(model: model, currentIdx: currentSelectedIndex) { (flag) in
//                debugPrint(flag)
//            }
//        }
//        self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
        
    }
//    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
//        if currentSelectedIndex >= (self.tableView.imgList?.count ?? 0) {
//            /// append
//            if let model = UserMediaListModel(JSON: ["localAsset": asset,
//                                                     "objType": asset.mediaType == .video ? 1 : 0]) {
//                model.uploadStatus = .ready
//                self.tableView.imgList?.append(model)
//                upload(model: model, currentIdx: currentSelectedIndex) { (flag) in
//                    debugPrint(flag)
//                }
//                self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
//            }
//        } else {
//            /// replace
//            let model = self.tableView.imgList?[currentSelectedIndex]
//            model?.objType = asset.mediaType == .video ? 1 : 0
//            model?.coverImg = nil
//            model?.href = nil
//            model?.localAsset = asset
//            model?.uploadStatus = .ready
//            self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
//            if let model = model {
//                upload(model: model, currentIdx: currentSelectedIndex) { (flag) in
//                    debugPrint(flag)
//                }
//            }
//        }
//        currentSelectedIndex = -1
//    }
//    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
//        tableView.imageAsset = asset
//        if let model = UserMediaListModel(JSON: ["localAsset": asset,
//                                                 "objType": asset.mediaType == .video ? 1 : 0]) {
//            model.uploadStatus = .ready
//            upload(model: model, currentIdx: currentSelectedIndex) { (flag) in
//                debugPrint(flag)
//            }
//        }
//        self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
//    }
    
//    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetsWith assets: [MTAsset]) {
//        if !(assets.count + currentSelectedIndex > 9) {
//            for i in 0..<assets.count {
//                let asset = assets[i]
//                if let model = UserMediaListModel(JSON: ["localAsset": asset,
//                                                         "objType": asset.mediaType == .video ? 1 : 0]) {
//                    model.uploadStatus = .ready
//                    self.tableView.imgList?.append(model)
//                    upload(model: model, currentIdx: i + currentSelectedIndex) { (flag) in
//                        debugPrint(flag)
//                    }
//                }
//            }
//            self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .none)
//        }
//        currentSelectedIndex = -1
//    }
    
}

// MARK: ------------------------------------ <#Comment#> ----------------------------------------
extension MineProfileController: MTTagViewControllerDelegate {
    
    func tagViewController(_ controller: MTTagViewController, successfullySavedWithTagType type: MTTagViewController.TagType, withSelectedModels models: [MTTagModel]) {
        if type == .personality {
            self.tableView.tags = models
        } else if type == .hobby {
            self.tableView.hobbies = models
        }
        self.tableView.reloadData()
    }
    
}
